package com.catazy.wanandroid.common_base.ext

import com.tencent.mmkv.MMKV

/**
 * 作者: Tao
 * 日期: 2024/5/8
 * 时间: 15:26
 * 描述: MMKV封装类
 */
object Prefs {

    private val mmkv = MMKV.defaultMMKV()!!

    fun put(key: String, value: Any) {
        when (value) {
            is String -> mmkv.encode(key, value)
            is Int -> mmkv.encode(key, value)
            is Boolean -> mmkv.encode(key, value)
            is Float -> mmkv.encode(key, value)
            is Long -> mmkv.encode(key, value)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }
    }

    fun putAsync(key: String, value: Any) {
        when (value) {
            is String -> mmkv.putString(key, value).apply()
            is Int -> mmkv.putInt(key, value).apply()
            is Boolean -> mmkv.putBoolean(key, value).apply()
            is Float -> mmkv.putFloat(key, value).apply()
            is Long -> mmkv.putLong(key, value).apply()
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }
    }

    fun get(key: String, default: Any): Any? {
        return when (default) {
            is String -> mmkv.decodeString(key, default)
            is Int -> mmkv.decodeInt(key, default)
            is Boolean -> mmkv.decodeBool(key, default)
            is Float -> mmkv.decodeFloat(key, default)
            is Long -> mmkv.decodeLong(key, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }
    }

    fun clear() {
        mmkv.clear().apply()
    }
}